from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
import logging
from datetime import datetime, date

from backend.database.session import get_db
from backend.database import crud
from backend.services import data_fetcher
from backend.schemas.schema import StockZTBase
from backend.schemas import APIResponse

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)



# 创建路由实例
router = APIRouter(prefix="/api", tags=["涨停股票"]) # type: ignore

@router.post("/save_zt_stocks", response_model=APIResponse[StockZTBase])
async def save_zt_stocks(
    date: str = Query(None, description="查询日期，格式为 YYYYMMDD"),
    db: AsyncSession = Depends(get_db)
):
    """
    从akshare获取涨停股票数据并保存到数据库
    
    Args:
        date: 查询日期，格式为 YYYYMMDD，如不提供则获取最新数据
    """
    try:
        # 从akshare获取数据
        zt_data = await data_fetcher.fetch_zt_stock_data(date)
        
        if not zt_data:
            return APIResponse[StockZTBase](
                success=True,
                data=[],
                count=0,
                message="未获取到数据"
            )
        
        # 清空当天数据（如果需要）
        # await crud.delete_stock_zt_by_date(datetime.now().date())
        
        # 批量保存到数据库
        response_data = await crud.batch_create_stock_zt(db,zt_data)
        
        # 转换数据格式
        # for item in zt_data:
        #     try:
        #         stock_data = StockZTBase(**item)
        #         response_data.append(stock_data)
        #     except Exception as e:
        #         logger.error(f"转换股票数据时出错: {str(e)}")
        #         continue
        
        return APIResponse[StockZTBase](
            success=True,
            data=response_data,
            count=len(response_data),
            message=f"成功保存 {len(response_data)} 条涨停股票数据"
        )
    except Exception as e:
        logger.error(f"保存涨停股票数据时发生错误: {str(e)}")
        raise HTTPException(status_code=500, detail=f"保存数据时发生错误: {str(e)}")

@router.get("/get_zt_stocks", response_model=APIResponse[StockZTBase])
async def get_zt_stocks(
    date: Optional[str] = Query(None, description="查询日期，格式为 YYYYMMDD"),
    db: AsyncSession = Depends(get_db)
):
    """
    从数据库获取涨停股票数据
    
    Args:
        date: 查询日期，格式为 YYYYMMDD
    """
    try:
        # 如果未提供日期，则默认查询今天的数据
        query_date = None
        if date:
            try:
                query_date = datetime.strptime(date, "%Y%m%d").date()
            except ValueError:
                raise HTTPException(status_code=400, detail="日期格式错误，应为YYYYMMDD")
        
        # 从数据库查询数据
        stocks = await crud.get_stock_zt_by_date(db, query_date)

        try:
            response_data = [StockZTBase.model_validate(stock) for stock in stocks]
        except Exception as e:
            logger.error(f"转换股票数据时出错: {str(e)}")
            response_data = []

        
        return APIResponse[StockZTBase](
            success=True,
            data=response_data,
            count=len(response_data),
            message=f"成功获取 {len(response_data)} 条涨停股票数据"
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取涨停股票数据时发生错误: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取数据时发生错误: {str(e)}")